import store from "@/store"
import * as $apis from "./index.js";
import config from "@/config/index.config.js";
import $mUtils from '@/common/utils.js';
import {
	encryptData
} from './encrypt.js';
const md5Util = require("./md5.js");
let encrypt = config.encrypt,
	scopes = config.scopes,
	serviceId = config.serviceId,
	md5 = config.md5,
	debug = config.debug;
const getSign = obj => {
	let keys = Object.keys(obj);
	keys.sort();
	let params = [];
	keys.forEach(e => {
		if (obj[e] != null) {
			params.push(e + '=' + obj[e]);
		}
	});
	params.push('key=' + serviceId);
	let paramStr = params.join('&');
	let signResult = md5Util.md5(paramStr).toUpperCase();
	return signResult;
};


let debounceHide = $mUtils.debounce(function() {
	uni.hideLoading();
}, 500)
let debounceShow = function(text) {
	uni.showLoading({
		title: text || '加载中'
	});
}
export const filter = (data, options) => {
	debounceHide();
	return new Promise((resolve, reject) => {
		let result = data.result || data.data;
		switch (result.errcode) {
			case 0: //数据接收成功并进行预订操作
				resolve(result.data || result);
				break;
			case 204: //未设置支付密码
				resolve(result.data || result);
				break;
			case 400000: //请求失败
				uni.showToast({
					title: data.msg,
					duration: 1000,
					icon: 'none'
				});
				reject("请求失败"+result.errcode);
				break;
			case 400832: //登录没有手机号
				// uni.showToast({
				// 	title: data.msg,
				// 	icon: "none",
				// 	duration: 2000
				// })
				uni.$emit('needPhone');
				resolve(result.data || result);
				break;
			case 400833: //登录没有绑定微信
				uni.showToast({
					title: data.msg,
					icon: "none",
					duration: 2000
				})
				resolve(result.data || result);
				break;
			case 400834: //返回
				uni.navigateBack({
					delta: 1
				})
				uni.showToast({
					title: data.msg,
					icon: "none",
					duration: 2000
				})
				reject("请求失败"+result.errcode);
				break;
			default:
				if (process.env.NODE_ENV == "development") {
					uni.showModal({
						title: '警告',
						content: `${JSON.stringify(options)}`
					})
				}
				reject("状态码有误！！！"+result.errcode);
				break;
		}
	})
}

function HTTPZ(obj, config) {
	for (let i in obj.data) {
		if (obj.data[i] === "" || obj.data[i] === undefined || obj.data[i] === "undefined" || obj.data[i] === null ||
			obj.data[
				i] === "null") {
			delete obj.data[i];
		}
	}
	// obj.data = $mUtils.encryptData(obj.data);
	return new Promise((resolve, reject) => {
		let options = {
			url: "",
			method: "GET",
			data: {},
			dataType: "json",
			header: {
				"content-type": "application/json",
				"X-requested-With": "XMLHttpRequest",
				"TOKEN": store.state.vuex_token || '',
				"request-app": serviceId || '',
				"scopes": scopes || '',
				"session_id": store.state.sessionId || ''
			},
			success: (res) => {
				debounceHide()
				let data = res.data;
				let code = data.code;
				// 状态码为200
				if (code == 200) {
					filter(data, options).then((res) => {
						resolve(res)
					});
				} else {
					switch (code) {
						case 301:
							//永久跳转
							uni.showModal({
								content: data.msg,
								success: function(rel) {
									if (rel.confirm) {
										uni.redirectTo({
											url: data.data.data.url,
											fail: function(res) {
												uni.showModal({
													content: '访问失败',
													showCancel: false
												});
											}
										});
									}
								}
							});
							break;
						case 302:
							//临时跳转
							uni.showModal({
								content: data.msg,
								success: function(rel) {
									if (rel.confirm) {
										uni.navigateTo({
											url: data.data.data.url,
											fail: function(res) {
												uni.showModal({
													content: '访问失败',
													showCancel: false
												});
											}
										});
									}
								}
							});
							break;
						case 401: //跳转到登录页 不做任何提示
						case 422:
							store.dispatch("reLogin");
							reject("未登陆，需要登陆，或登陆已过期");
							break;
						case 403: // 请求失败
							uni.showToast({
								title: data.msg,
								icon: "none",
								duration: 2000
							})
							reject("请求失败");
							break;
						case 500: //alert弹窗弹出后台返回的msg
							uni.showModal({
								title: '提示',
								content: data.msg,
								showCancel: false,
								confirmColor: '#0DE5CE'
							})
							reject("服务器错误（弹出msg内容）");
							break;
						default:
							console.log(res)
							// uni.showModal({
							// 	title: '警告',
							// 	content: `${obj.msg}`
							// })
							break;
					}
					reject("HTTP:状态码异常！");
				}
			},
			fail: (err) => {
				console.log('err', err)
				debounceHide()
				uni.showToast({
					title: "网络异常，请稍后再试!",
					icon: "none",
				})
				reject("网络异常，请稍后再试!");
			},
			complete: () => {}
		}

		options = {
			...options,
			...obj
		};
		options.data.token = store.state.vuex_token;
		// options.data.scopes = scopes;
		if (debug) {
			console.log(options.data, 'options.data')
		}
		if (encrypt) {
			options.data = {
				param: encryptData(options.data)
			}
		}
		if(md5 && !encrypt){
			options.data.sign = getSign(options.data)
		}
		if (debug) {
			console.log(options.data, 'options.datan')
		}
		if (options.url && options.method) {
			uni.request(options);
		} else {
			uni.showToast({
				title: 'HTTP：缺失参数',
				icon: "none",
				duration: 2000
			})
		}
	})
}

function HTTP(obj, config) {
	if (!obj.data.isAlertLoad) {
		debounceShow(obj.data.apiLoadText);
		delete obj.data.apiLoadText;
	}
	return new Promise((resolve, reject) => {
		HTTPZ(obj, config).then((res) => {
			resolve(res);
		});
	})
}



export default {
	filter,
	GET(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "GET"
		}, config);
	},
	POST(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	},
	PUT(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "PUT"
		}, config);
	},
	POSTformdata(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	}
}
